//
//  SimpleRefreshHeader.swift
//  App_Common_Views
//
//  Created by 蒋晨成 on 2022/1/14.
//

import Chain
import Foundation
import PullToRefreshKit
import SnapKit
import UICore
import UIKit

public class SimpleRefreshHeader: UIView {
    public var triggerHeightForRefreshingState: CGFloat = 0

    private lazy var textForStateDic = [RefreshHeaderState: String]()

    private lazy var titleLabel: UILabel = .init()
        .x
        .textAlignment(.center)
        .textColor(.lightGray)
        .font(.systemFont(ofSize: 14))
        .instance

    private lazy var activityIndicator: UIActivityIndicatorView = {
        let activityIndicator = UIActivityIndicatorView(style: .large)
        activityIndicator.color = .lightGray
        activityIndicator.hidesWhenStopped = true
        return activityIndicator
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") }
}

public extension SimpleRefreshHeader {
    func prefersLargeTitles(_ prefersLargeTitles: Bool) {
        titleLabel.x.add(to: self).snp.remakeConstraints { maker in
            maker.centerX.equalToSuperview()
            if prefersLargeTitles {
                maker.bottom.equalToSuperview().offset(30)
            } else {
                maker.centerY.equalToSuperview()
            }
        }
    }

    func setText(_ text: String, mode: RefreshHeaderState) {
        textForStateDic[mode] = text
    }
}

private extension SimpleRefreshHeader {
    func setupUI() {
        activityIndicator.x.add(to: self).snp.makeConstraints { maker in
            maker.center.equalToSuperview()
        }
        titleLabel.x.add(to: self).snp.makeConstraints { maker in
            maker.center.equalToSuperview()
        }
    }
}

extension SimpleRefreshHeader: RefreshableHeader {
    public func heightForHeader() -> CGFloat {
        50.0
    }

    public func heightForRefreshingState() -> CGFloat {
        triggerHeightForRefreshingState > 0 ? triggerHeightForRefreshingState : heightForHeader()
    }

    public func heightForFireRefreshing() -> CGFloat {
        triggerHeightForRefreshingState > 0 ? triggerHeightForRefreshingState : heightForHeader()
    }

    public func stateDidChanged(_: RefreshHeaderState, newState: RefreshHeaderState) {
        let text = textForStateDic[newState]
        titleLabel.text = text
    }

    public func didBeginRefreshingState() {
        activityIndicator.isHidden = false
        titleLabel.isHidden = true
        activityIndicator.startAnimating()
    }

    public func didBeginHideAnimation(_: RefreshResult) {
        activityIndicator.stopAnimating()
    }

    public func didCompleteHideAnimation(_: RefreshResult) {
        activityIndicator.isHidden = true
        titleLabel.isHidden = false
    }
}
